
import Game from "../game/Game";
import { GameStateType } from "../game/GameStateType";

import BulletScript from "./BulletScript";
import SoundMgr from "../sound/SoundMgr";
import SoundType from "../sound/SoundType";


export default class PlayerScript extends Laya.Script3D {

    private _weapon: Laya.Sprite3D;
    private _rotationSpeed: number = 0.003;
    private _preFireTime: number = Laya.Browser.now();


    public get weapon() {
        if (this._weapon == null) {
            this._weapon = this.getWeapon();
        }
        return this._weapon;
    }

    public set preFireTime(value){
        this._preFireTime=value;
    }

    public onAwake(): void {
        this._weapon = this.getWeapon();
    }

    private getWeapon(): Laya.Sprite3D {
        return this.owner.getChildByName("weapon") as Laya.Sprite3D;
    }

   
    public onUpdate(): void {
        if (Game.state == GameStateType.BATTLING) {
            if (Game.isPress) {
                this._weapon.transform.rotate(new Laya.Vector3(0, this._rotationSpeed * Laya.timer.delta, 0), false, true);
            }
            if ((Laya.Browser.now() - this._preFireTime) > Game.hero.playerData.attackSpeedValue) {

                this._preFireTime = Laya.Browser.now();
                this.fire();

            }
        }
    }

    public fire() {
        for (let i = 0; i < Game.hero.bullet.fireDatas.length; i++) {
            // console.log("fire _fireDatas",Game.hero.bullet.fireDatas[i])
            SoundMgr.Ins.playEffect(SoundType.FIRE);
            let muzzle = Game.hero.bullet.getMuzzle(i);
            Game.layer3d.addChildAt(muzzle, 0)

            muzzle.particleSystem.play();
            muzzle.transform.position = Game.hero.bullet.fireDatas[i].firePos.transform.position;

            let projectile = Game.hero.bullet.getProjectile(i);
            Game.layer3d.addChildAt(projectile, 0);

            let bulletScript: BulletScript = projectile.getComponent(BulletScript);
            bulletScript.setDirection(Game.hero.bullet.fireDatas[i].firePos.transform)
          
        }

    }


}